<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">



  
  
    
    
  <script src="/myblog/lib/pace/pace.min.js?v=1.0.2"></script>
  <link href="/myblog/lib/pace/pace-theme-minimal.min.css?v=1.0.2" rel="stylesheet">







<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/myblog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/myblog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/myblog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/myblog/images/apple-touch-icon.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/myblog/images/favicon-32x32.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/myblog/images/favicon-16x16.png?v=5.1.4">


  <link rel="mask-icon" href="/myblog/images/safari-pinned-tab.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="java,jvm,虚拟机,读书笔记,">










<meta name="description" content="判断对象是否存活一、引用计数算法​    给对象中添加一个引用计数器，每当有一个地方引用他时就给计数器值加一；当引用失效时，计数器值就减一；任何时刻计数器为0的对象就是不可能再被使用的。 ​    缺点：很难解决对象之间互相循环引用的问题。 二、可达性分析算法​    以“GC Root”对象为起始点，从此节点向下搜索，搜索所走的路径成为引用链，当一个对象和GC Root之间没有任何引用链的时候，">
<meta name="keywords" content="java,jvm,虚拟机,读书笔记">
<meta property="og:type" content="article">
<meta property="og:title" content="java虚拟机笔记（二）">
<meta property="og:url" content="https://github.com/lgsxiaosen/post/f5c7bd9e.html">
<meta property="og:site_name" content="Learning Notes">
<meta property="og:description" content="判断对象是否存活一、引用计数算法​    给对象中添加一个引用计数器，每当有一个地方引用他时就给计数器值加一；当引用失效时，计数器值就减一；任何时刻计数器为0的对象就是不可能再被使用的。 ​    缺点：很难解决对象之间互相循环引用的问题。 二、可达性分析算法​    以“GC Root”对象为起始点，从此节点向下搜索，搜索所走的路径成为引用链，当一个对象和GC Root之间没有任何引用链的时候，">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://raw.githubusercontent.com/lgsdaredevil/newblog/resource-newblog/source/favicons/article/%E5%8F%AF%E8%BE%BE%E6%80%A7%E5%88%86%E6%9E%90%E7%AE%97%E6%B3%95%E5%9B%BE%E7%89%87.png">
<meta property="og:image" content="https://raw.githubusercontent.com/lgsdaredevil/newblog/resource-newblog/source/favicons/article/%E5%9E%83%E5%9C%BE%E6%94%B6%E9%9B%86%E7%AE%97%E6%B3%95.jpg">
<meta property="og:updated_time" content="2019-01-19T08:29:23.059Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="java虚拟机笔记（二）">
<meta name="twitter:description" content="判断对象是否存活一、引用计数算法​    给对象中添加一个引用计数器，每当有一个地方引用他时就给计数器值加一；当引用失效时，计数器值就减一；任何时刻计数器为0的对象就是不可能再被使用的。 ​    缺点：很难解决对象之间互相循环引用的问题。 二、可达性分析算法​    以“GC Root”对象为起始点，从此节点向下搜索，搜索所走的路径成为引用链，当一个对象和GC Root之间没有任何引用链的时候，">
<meta name="twitter:image" content="https://raw.githubusercontent.com/lgsdaredevil/newblog/resource-newblog/source/favicons/article/%E5%8F%AF%E8%BE%BE%E6%80%A7%E5%88%86%E6%9E%90%E7%AE%97%E6%B3%95%E5%9B%BE%E7%89%87.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/myblog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://github.com/lgsxiaosen/post/f5c7bd9e.html">





<script>
    (function () {
        if ('') {
            if (prompt('请输入文章密码') !== '') {
                alert('密码错误！');
                if (history.length === 1) {
                    location.replace("https://lgsdaredevil.github.io/myblog"); // 这里替换成你的首页
                } else {
                    history.back();
                }
            }
        }
    })();
</script>
  <title>java虚拟机笔记（二） | Learning Notes</title>
  








</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/myblog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Learning Notes</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/myblog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/myblog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/myblog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/myblog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/myblog/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br>
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/myblog/404.html" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br>
            
            公益404
          </a>
        </li>
      
        
        <li class="menu-item menu-item-comments">
          <a href="/myblog/comments" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br>
            
            留言板
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://github.com/lgsxiaosen/myblog/post/f5c7bd9e.html">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="小森">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/myblog/images/android-chrome-192x192.png">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Learning Notes">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">java虚拟机笔记（二）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-08-04T09:35:56+08:00">
                2018-08-04
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing">
                  <a href="/myblog/categories/技术文章/" itemprop="url" rel="index">
                    <span itemprop="name">技术文章</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o">本文总阅读量</i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="判断对象是否存活"><a href="#判断对象是否存活" class="headerlink" title="判断对象是否存活"></a>判断对象是否存活</h1><h3 id="一、引用计数算法"><a href="#一、引用计数算法" class="headerlink" title="一、引用计数算法"></a>一、引用计数算法</h3><p>​    给对象中添加一个引用计数器，每当有一个地方引用他时就给计数器值加一；当引用失效时，计数器值就减一；任何时刻计数器为0的对象就是不可能再被使用的。</p>
<p>​    缺点：很难解决对象之间互相循环引用的问题。</p>
<h3 id="二、可达性分析算法"><a href="#二、可达性分析算法" class="headerlink" title="二、可达性分析算法"></a>二、可达性分析算法</h3><p>​    以“GC Root”对象为起始点，从此节点向下搜索，搜索所走的路径成为引用链，当一个对象和GC Root之间没有任何引用链的时候，则此对象为不可用对象。</p>
<p><img src="https://raw.githubusercontent.com/lgsdaredevil/newblog/resource-newblog/source/favicons/article/%E5%8F%AF%E8%BE%BE%E6%80%A7%E5%88%86%E6%9E%90%E7%AE%97%E6%B3%95%E5%9B%BE%E7%89%87.png" alt="可达性分析算法判断对象是否可以回收"></p>
<p>如上图所示，Object1到Object4与GC Root之间存在引用链，所以Object1到Object4的对象是可达对象，而Object5和Object6没有雨GC Root相关的引用链，所以Object5和Object6是不可达对象，是可以回收的对象。</p>
<p>​    Java中可以被称为GC Root的对象有以下几种：</p>
<ul>
<li><p>虚拟机栈中引用的对象</p>
</li>
<li><p>方法区中类静态属性引用的对象</p>
</li>
<li><p>方法区中常量引用的对象</p>
</li>
<li><p>本地方法栈中JNI（Native方法）引用的对象</p>
</li>
</ul>
<h3 id="三、四种引用类型"><a href="#三、四种引用类型" class="headerlink" title="三、四种引用类型"></a>三、四种引用类型</h3><ul>
<li><p>强引用：类似于new一个对象的引用，只要强引用存在，垃圾收集器永远不会回收掉被引用的对象。</p>
</li>
<li><p>软引用：描述的是一些还有用但并非必须的对象，对于软引用关联的对象，在系统将要发生内存溢出之前，会把这些对象列进回收范围之中进行第二次回收，如果这次回收还没有足够的内存就会抛出内存溢出异常。</p>
</li>
<li><p>弱引用：描述非必须对象，被弱引用关联的对象只能生存到下一次垃圾收集发生之前。当垃圾收集器工作时，无论当前内存是否足够，都会回收只被弱引用关联的对象。</p>
</li>
<li><p>虚引用：一个对象是否有虚引用存在，完全不会对其生存时间构成影响，也无法通过虚引用来取得一个对象实例。为一个对象设置虚引用关联的唯一目的就是当这个对象被收集器收集时会收到一个系统通知。</p>
</li>
</ul>
<p>如果一个对象在可达性分析时没后没有与GC Root相连接的引用链，它将会第一次标记并筛选，筛选条件是该对象是否有必要执行finalize()方法，如果有必要执行finalize()方法，对象只要重新与引用链上的任何一个对象建立关联即可，拿在第二次标记时将他移除“即将回收”集合。任何对象的finalize()方法只会被调用一次，如果对象面临下一次回收，它的finalize()方法不会被再次执行。</p>
<h1 id="垃圾收集算法"><a href="#垃圾收集算法" class="headerlink" title="垃圾收集算法"></a>垃圾收集算法</h1><h3 id="一、标记—清除算法"><a href="#一、标记—清除算法" class="headerlink" title="一、标记—清除算法"></a>一、标记—清除算法</h3><p>​    首先标记出所有要回收的对象，在标记完成后统一回收被标记的对象。</p>
<p>​    缺点：1、效率问题，标记和清除两个过程的效率都不高。<br>           2、空间问题，标记清除会产生大量不连续的内存碎片，空间碎片太多会导致以后程序运行过程中需要分配较大对象时，无法找到足够的连续内存而不得进行另一次垃圾收集动作。</p>
<h3 id="二、复制算法"><a href="#二、复制算法" class="headerlink" title="二、复制算法"></a>二、复制算法</h3><p>​    将内存安容量分为大小相等的两块，每次只使用其中一块，当着一块内存用完后，将存活的对象复制到另一块上面，再把已使用的内存清理掉。</p>
<p>​    一般虚拟机是将内存分为一块较大的Eden空间和两块较小的Survivor空间。每次使用？Eden和其中一块Survivor，回收时，将Eden和Survivor还存后的对象复制到Survivor空间，再清理掉刚才用到的Survivor和Eden空间。当Survivor内存不足时会用到其他内存（老年代）进行分配担保。</p>
<p>​    缺点：在对象存活率较高时就要进行较多的复制操作，效率会变低，老年代一般不能直接选用这种做法。</p>
<h3 id="三、标记—整理算法"><a href="#三、标记—整理算法" class="headerlink" title="三、标记—整理算法"></a>三、标记—整理算法</h3><p>​    标记过程与标记—清除算法相同，然后让所有存活的对象都像一端移动，然后直接清理掉端边界以外的内存。适用于老年代整理。</p>
<p><img src="https://raw.githubusercontent.com/lgsdaredevil/newblog/resource-newblog/source/favicons/article/%E5%9E%83%E5%9C%BE%E6%94%B6%E9%9B%86%E7%AE%97%E6%B3%95.jpg" alt="三种垃圾收集算法图片"></p>
<h3 id="四、分代收集算法"><a href="#四、分代收集算法" class="headerlink" title="四、分代收集算法"></a>四、分代收集算法</h3><p>​    一般根据对象存活周期将对象划分为几块。Java堆分为新生代和老年代。新生代一般采用复制算法，而老年代对象存活较高，没有额外空间对它进行分配担保，就必须使用标记—清除或标记—整理算法。</p>
<h1 id="垃圾收集器"><a href="#垃圾收集器" class="headerlink" title="垃圾收集器"></a>垃圾收集器</h1><h3 id="一、Serial收集器"><a href="#一、Serial收集器" class="headerlink" title="一、Serial收集器"></a>一、Serial收集器</h3><p>​    是虚拟机在client模式下默认的新生代收集器，是单线程收集器，必须停掉其他所有工作线程，知道他收集结束。</p>
<h3 id="二、ParNew收集器"><a href="#二、ParNew收集器" class="headerlink" title="二、ParNew收集器"></a>二、ParNew收集器</h3><p>​    时Serial收集器的多线程版本。是许多运行在server模式下的虚拟机的首选的新生代收集器。除了Serial收集器外，只有它能与CMS收集器配合工作。</p>
<h3 id="三、Parallel-Scavenge收集器"><a href="#三、Parallel-Scavenge收集器" class="headerlink" title="三、Parallel Scavenge收集器"></a>三、Parallel Scavenge收集器</h3><p>​    并行多线程的新生代收集器。CMS等收集器的特点是尽可能缩短垃圾收集时用户线程的停顿时间，而Parallel Scavenge收集器的目的是达到一个可控制吞吐量。吞吐量是指CPU用于运行用户代码的时间与CPU总消耗的时间的比值</p>
<h3 id="四、Serial-Old收集器"><a href="#四、Serial-Old收集器" class="headerlink" title="四、Serial Old收集器"></a>四、Serial Old收集器</h3><p>​    是Serial收集器的老年代版本，单线程收集器。主要是给client模式下的虚拟机使用。在server模式下：一是可以与Parallel Scavenge收集器配合使用。另一方面是作为CMS收集器的后备方案。</p>
<h3 id="五、Parallel-Old收集器"><a href="#五、Parallel-Old收集器" class="headerlink" title="五、Parallel Old收集器"></a>五、Parallel Old收集器</h3><p>​    是Parallel Scavenge收集器的老年代版本，使用多线程和标记—整理算法。</p>
<h3 id="六、CMS收集器"><a href="#六、CMS收集器" class="headerlink" title="六、CMS收集器"></a>六、CMS收集器</h3><p>​    是一种以获取最短回收时间为目标的收集器。基于标记—清除算法实现。运作过程：</p>
<ol>
<li>初始标记</li>
<li>并发标记</li>
<li>重新标记</li>
<li>并发清除</li>
</ol>
<p>其中初始标记和重新标记需要“stop the world”，并发标记和并发清除是和用户线程一起进行的。</p>
<p>缺点：1、对CPU资源敏感，因为占用了一部分线程而导致应用程序变慢，总吞吐量会降低。</p>
<p>​       2、收集器无法处理浮动垃圾。</p>
<p>​       3.采用标记—清除算法会产生大量空间碎片。</p>
<h3 id="七、G1收集器"><a href="#七、G1收集器" class="headerlink" title="七、G1收集器"></a>七、G1收集器</h3><p>​    面向服务端应用的垃圾收集器。优点如下：</p>
<ul>
<li><p>并行并发</p>
</li>
<li><p>分代收集</p>
</li>
<li><p>空间整合</p>
</li>
<li><p>可预测停顿</p>
</li>
</ul>
<p>它将整个Java堆分为多个大小相等的独立区域，保留新生代和老年代概念，但他们不是物理隔离，都是一部分Region的集合。G1跟踪各个Region里面的垃圾堆积的价值大小，在后台维护一个优先列表，每次根据允许的手机时间，优先回收价值大的Region。</p>
<p>G1的操作步骤：</p>
<ul>
<li>初始标记</li>
<li>并发标记</li>
<li>最终标记</li>
<li>筛选回收</li>
</ul>
<h1 id="内存分配与回收策略"><a href="#内存分配与回收策略" class="headerlink" title="内存分配与回收策略"></a>内存分配与回收策略</h1><h3 id="一、对象优先在Eden分配"><a href="#一、对象优先在Eden分配" class="headerlink" title="一、对象优先在Eden分配"></a>一、对象优先在Eden分配</h3><h3 id="二、大对象直接进入老年代"><a href="#二、大对象直接进入老年代" class="headerlink" title="二、大对象直接进入老年代"></a>二、大对象直接进入老年代</h3><p>​    需要大量连续的内存空间的Java对象，最典型就是很长的字符串以及数组。</p>
<h3 id="三、长期存活的对象进入老年代"><a href="#三、长期存活的对象进入老年代" class="headerlink" title="三、长期存活的对象进入老年代"></a>三、长期存活的对象进入老年代</h3><p>​    虚拟机给每一个对象定义年龄计数器，在Eden代出生并经过一次Minor GC仍存后，并能被Survivor接收，被移到Survivor空间中，年龄加一。在Survivor中每熬过一次GC，年龄就加一。当年龄到一定长度后就进入老年代。</p>
<h3 id="四、动态对象年龄判断"><a href="#四、动态对象年龄判断" class="headerlink" title="四、动态对象年龄判断"></a>四、动态对象年龄判断</h3><p>​    如果在Survivor中的相同年龄所有对象大小的总和大于Survivor空间的一半，年龄大于等于改年龄的对象就会进入老年代。</p>
<h3 id="五、空间分配担保"><a href="#五、空间分配担保" class="headerlink" title="五、空间分配担保"></a>五、空间分配担保</h3><p>​    在Minor GC前虚拟机会先检查老年代最大可用的连续空间是否大于新生代所有对象的总空间，如果条件成立，那么Minor GC可以确保安全。否则虚拟机会查看HandelPromotionFailure设置的值是否允许担保失败，如果是，则在检查老年代最大可用的连续空间是否大于历次晋升到老年代对象的平均大小，如果大于，尝试进行一次Minor GC。否则进行一次Full GC</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>如果觉得我的文章对您有用，请随意打赏。您的支持将鼓励我继续创作!</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="https://raw.githubusercontent.com/lgsdaredevil/newblog/master/css/images/wechatlike.jpg" alt="小森 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="https://raw.githubusercontent.com/lgsdaredevil/newblog/master/css/images/alipay.png" alt="小森 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/myblog/tags/java/" rel="tag"><i class="fa fa-tag"></i> java</a>
          
            <a href="/myblog/tags/jvm/" rel="tag"><i class="fa fa-tag"></i> jvm</a>
          
            <a href="/myblog/tags/虚拟机/" rel="tag"><i class="fa fa-tag"></i> 虚拟机</a>
          
            <a href="/myblog/tags/读书笔记/" rel="tag"><i class="fa fa-tag"></i> 读书笔记</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/myblog/post/c5d15146.html" rel="next" title="java虚拟机笔记（一）">
                <i class="fa fa-chevron-left"></i> java虚拟机笔记（一）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/myblog/post/b8d91ecc.html" rel="prev" title="java虚拟机笔记（三）">
                java虚拟机笔记（三） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      
        <div onclick="showGitment()" id="gitment-display-button">显示 Gitment 评论</div>
        <div id="gitment-container" style="display:none"></div>
      
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/myblog/images/android-chrome-192x192.png" alt="小森">
            
              <p class="site-author-name" itemprop="name">小森</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/myblog/archives/">
              
                  <span class="site-state-item-count">41</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/myblog/categories/index.html">
                  <span class="site-state-item-count">3</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/myblog/tags/index.html">
                  <span class="site-state-item-count">24</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/lgsxiaosen/myblog" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#判断对象是否存活"><span class="nav-number">1.</span> <span class="nav-text">判断对象是否存活</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#一、引用计数算法"><span class="nav-number">1.0.1.</span> <span class="nav-text">一、引用计数算法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#二、可达性分析算法"><span class="nav-number">1.0.2.</span> <span class="nav-text">二、可达性分析算法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#三、四种引用类型"><span class="nav-number">1.0.3.</span> <span class="nav-text">三、四种引用类型</span></a></li></ol></li></ol><li class="nav-item nav-level-1"><a class="nav-link" href="#垃圾收集算法"><span class="nav-number">2.</span> <span class="nav-text">垃圾收集算法</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#一、标记—清除算法"><span class="nav-number">2.0.1.</span> <span class="nav-text">一、标记—清除算法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#二、复制算法"><span class="nav-number">2.0.2.</span> <span class="nav-text">二、复制算法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#三、标记—整理算法"><span class="nav-number">2.0.3.</span> <span class="nav-text">三、标记—整理算法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#四、分代收集算法"><span class="nav-number">2.0.4.</span> <span class="nav-text">四、分代收集算法</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#垃圾收集器"><span class="nav-number">3.</span> <span class="nav-text">垃圾收集器</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#一、Serial收集器"><span class="nav-number">3.0.1.</span> <span class="nav-text">一、Serial收集器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#二、ParNew收集器"><span class="nav-number">3.0.2.</span> <span class="nav-text">二、ParNew收集器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#三、Parallel-Scavenge收集器"><span class="nav-number">3.0.3.</span> <span class="nav-text">三、Parallel Scavenge收集器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#四、Serial-Old收集器"><span class="nav-number">3.0.4.</span> <span class="nav-text">四、Serial Old收集器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#五、Parallel-Old收集器"><span class="nav-number">3.0.5.</span> <span class="nav-text">五、Parallel Old收集器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#六、CMS收集器"><span class="nav-number">3.0.6.</span> <span class="nav-text">六、CMS收集器</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#七、G1收集器"><span class="nav-number">3.0.7.</span> <span class="nav-text">七、G1收集器</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#内存分配与回收策略"><span class="nav-number">4.</span> <span class="nav-text">内存分配与回收策略</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#一、对象优先在Eden分配"><span class="nav-number">4.0.1.</span> <span class="nav-text">一、对象优先在Eden分配</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#二、大对象直接进入老年代"><span class="nav-number">4.0.2.</span> <span class="nav-text">二、大对象直接进入老年代</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#三、长期存活的对象进入老年代"><span class="nav-number">4.0.3.</span> <span class="nav-text">三、长期存活的对象进入老年代</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#四、动态对象年龄判断"><span class="nav-number">4.0.4.</span> <span class="nav-text">四、动态对象年龄判断</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#五、空间分配担保"><span class="nav-number">4.0.5.</span> <span class="nav-text">五、空间分配担保</span></a></li></ol></li></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

<div class="copyright">&copy; <span itemprop="copyrightYear">2019</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">小森</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




<!-- <div class="powered-by">
<i class="fa fa-user-md"></i><span id="busuanzi_container_site_uv">
  本站访客数:<span id="busuanzi_value_site_uv"></span>
</span>
</div> -->

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user">本站访客数</i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye">本站总访问量</i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  









  



  
  
    <script type="text/javascript" src="/myblog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/myblog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/myblog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/myblog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/myblog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/myblog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/myblog/lib/canvas-nest/canvas-nest.min.js"></script>
  

  
  
    <script id="ribbon" type="text/javascript" size="300" alpha="0.6" zindex="-1" src="/myblog/lib/canvas-ribbon/canvas-ribbon.js"></script>
  


  


  <script type="text/javascript" src="/myblog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/myblog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/myblog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/myblog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/myblog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/myblog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/myblog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  







<!-- LOCAL: You can save these files to your site and update links -->
    
        
        <link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css">
        <!-- <script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script> -->
        <script src="https://www.wenjunjiang.win/js/gitment.js"></script>
    
<!-- END LOCAL -->

    
      <style>
        a.gitment-editor-footer-tip { display: none; }
        .gitment-container.gitment-footer-container { display: none; }
      </style>
    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitment({
            id: window.location.pathname, 
            owner: 'lgsxiaosen',
            repo: 'myblog',
            
            oauth: {
            
            
                client_secret: '876f37e17b73ba2870db494ed0b23e3194068dc9',
            
                client_id: '63acdc65d11c172104c4'
            }});
        gitment.render('gitment-container');
      }

      
      function showGitment(){
        document.getElementById("gitment-display-button").style.display = "none";
        document.getElementById("gitment-container").style.display = "block";
        renderGitment();
      }
      
      </script>
    







  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/myblog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

<script src="/myblog/live2dw/lib/L2Dwidget.min.js?0c58a1486de42ac6cc1c59c7d98ae887"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","model":{"jsonPath":"/myblog/live2dw/assets/wanko.model.json"},"display":{"position":"right","width":80,"height":200},"mobile":{"show":true},"log":false,"tagMode":false});</script></body>
</html>
